'use client';

import hljs from 'highlight.js';
import 'highlight.js/styles/github-dark.css'; // or your preferred theme
import { useEffect, useRef } from 'react';

interface HighlightProps {
  content: string;
}

export const Highlight = ({ content }: HighlightProps) => {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (ref.current) {
      // Use a regular expression to wrap code blocks in <pre><code>...</code></pre>
      const safeContent = typeof content === 'string' ? content : '';
      const highlightedContent = safeContent.replace(/```(.*?)\n([\s\S]*?)```/g, (match, lang, code) => {
        const language = hljs.getLanguage(lang) ? lang : 'plaintext';
        const highlightedCode = hljs.highlight(code, { language }).value;
        return `<pre><code class="hljs ${language}">${highlightedCode}</code></pre>`;
      });

      ref.current.innerHTML = highlightedContent;
    }
  }, [content]);

  return <div ref={ref} className="prose prose-lg dark:prose-invert max-w-none" />;
};